package weaver.interfaces.gyxy.rabbitmq.config;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 1. 自定义连接池工厂
 **/
public class RabbitMqChannelPoolFactory implements PooledObjectFactory<Channel> {

    private Connection connection;

    public RabbitMqChannelPoolFactory(){
        try {
            //创建连接工厂
            ConnectionFactory factory = new ConnectionFactory();
            factory.setRequestedHeartbeat(0);
            //设置host
            factory.setHost("58.193.84.162");
            factory.setPort(5672);
            factory.setUsername("wxgyoa");
            factory.setPassword("a123123+");
            factory.setVirtualHost("/");
            factory.setConnectionTimeout(15000);
            connection = factory.newConnection();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }

    @Override
    public PooledObject<Channel> makeObject() throws Exception {
        // 池对象创建实例化资源
        
        Channel channel = connection.createChannel();

        channel.confirmSelect();

        //添加监听器
        //channel.addConfirmListener(new RabbitmqConfirmListener());
        channel.addReturnListener( new RabbitmqRetrurnListener());
        return new DefaultPooledObject<>(channel);
    }

    @Override
    public void destroyObject(PooledObject<Channel> p) throws Exception {
        // 池对象销毁资源
        if (p != null && p.getObject() != null && p.getObject().isOpen()) {
            p.getObject().close();
        }
    }

    @Override
    public boolean validateObject(PooledObject<Channel> p) {
        // 验证资源是否可用
        return p.getObject() != null && p.getObject().isOpen();
    }

    @Override
    public void activateObject(PooledObject<Channel> p) {

    }

    @Override
    public void passivateObject(PooledObject<Channel> p) {

    }
}
